package book.manager.service.Impl;

import book.manager.entity.AuthUser;
import book.manager.mapper.UserMapper;
import book.manager.service.AuthService;
import lombok.extern.java.Log;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Log
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    UserMapper mapper;
    @Resource
    BCryptPasswordEncoder encoder;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean register(String username, String sex, String grade, String password) {
        AuthUser user = new AuthUser(0, username, "user", encoder.encode(password));
        try {
            if (mapper.registerUser(user) <= 0) {
                log.warning("用户基本信息添加失败");
                return false;
            }
            if (mapper.addStudentInfo(user.getId(), username, sex, grade) <= 0) {
                log.warning("学生详细信息添加失败");
                return false;
            }
        } catch (Exception ignored) {
            // 手动回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Override
    public AuthUser findUser(HttpSession session) {
        AuthUser user = (AuthUser) session.getAttribute("user");
        if (user == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            user = mapper.getUserByUsername(authentication.getName());
            session.setAttribute("user", user);
        }
        return user;
    }
}
